import store from '../../vuex/store';
import router from '../../config/routes';
import $ from 'jquery';
import Util from '../../common/util.js';

/**
 * 处理用户默认会话行为
 */
export default {
	/**
	 * 初始化会话信息
	 * @return {[type]} [description]
	 */
	init: function() {
		//刷新accessToken
		store.dispatch('authFlushToken');
		let token = store.getters.auth_token;
		if(token && token.tokenValue) {
			this.vadToken();
		}
	},
	/**
	 * 验证会话
	 * @return {[type]} [description]
	 */
	vadToken: function() {
		//初始化accessToken
		let tokenId = store.getters.auth_token_id;
		var obj = this;
		$.ajax({
			url: '/ws/oauth/vad',
			type: 'GET',
			async: false, //同步请求
			beforeSend: function(request) {
				request.setRequestHeader('Authorization', "Bearer " + tokenId);
			},
			success: function(data,textStatus,jqXHR){
				if(data.meta.code == 0) {
					obj.initUserContext();
				} else {
					store.dispatch('authLogout');
					window.location.href = Util.loginPath();
				}
			},
			error:function(xhr,textStatus){
				obj.refreshToken();
			}
		});
	},
	/**
	 * 刷新TOKEN
	 */
	refreshToken: function() {
		let params = {
			grantType: 'refresh_token',
			refreshToken: store.getters.auth_refresh_token_id
		};
		var obj = this;
		$.ajax({
			url: '/woauth/token',
			type: 'POST',
			contentType:"application/json",
			data: JSON.stringify(params),
			async: false, //同步请求
			success: function(data,textStatus,jqXHR){
				if(data.meta.code == 0) {
					let tokenData = data.data;
					localStorage.setItem(Util.tokenKey(), JSON.stringify(tokenData));
					store.dispatch('authFlushToken');

					obj.initUserContext();
				} else {
					store.dispatch('authLogout');
					window.location.href = Util.loginPath();
				}
			},
			error:function(xhr,textStatus){
				store.dispatch('authLogout');
				window.location.href = Util.loginPath();
			}
		});
	},
	/**
	 * 初始化用户信息
	 * @return {[type]} [description]
	 */
	initUserContext: function() {
		window.location.href = Util.homePath();		
	}
}